package com.zkw.concurrent.executors

import java.util.concurrent.ForkJoinPool
import java.util.concurrent.RecursiveAction

/**
 * Created by Administrator on 2016/4/8.
 */
class RecursiveActionMain extends RecursiveAction {

    private def workLoad = 0

    RecursiveActionMain(def workLoad){
        this.workLoad = workLoad;
    }

    @Override
    protected void compute() {
        //if work is above threshold, break tasks up into smaller tasks
        if (this.workLoad > 8){
            println 'splitting workload:'+this.workLoad
            for (RecursiveAction recursiveAction : createSubtasks()){
                recursiveAction.fork()
            }
        } else {
            println 'doing workload myself: '+this.workLoad
        }
    }

    private List<RecursiveActionMain> createSubtasks(){
        def subtasks = new ArrayList<RecursiveActionMain>()
        def subtask1 = new RecursiveActionMain(this.workLoad/2)
        def subtask2 = new RecursiveActionMain(this.workLoad/2)
        subtasks.add(subtask1)
        subtasks.add(subtask2)

        return subtasks
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool(4)
        RecursiveActionMain recursiveAction = new RecursiveActionMain(100);
        forkJoinPool.invoke(recursiveAction)
    }
}
